package com.gk.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gk.bean.GuoYaoBackDto.GHttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {
    //controller层之前执行
    @Value("${guoyao.common.hzid}")
    private int hzid;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        int id = 0;
        try {
            id = Integer.parseInt(request.getHeader("id"));
        } catch (Exception e) {
            GHttpResult resultData = new GHttpResult();
            resultData.setCode(-202);
            resultData.setMessage("请求头参数解析异常");
            log.error(JSON.toJSONString(resultData));
            response.getWriter().print(JSONObject.toJSONString(resultData));
            return false;
        }
        if (hzid != id) {
            GHttpResult resultData = new GHttpResult();
            resultData.setCode(-202);
            resultData.setMessage("货主Id校验失败");
            log.error(JSON.toJSONString(resultData));
            response.getWriter().print(JSONObject.toJSONString(resultData));
            return false;
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion");
    }


}
